package group.raber.dataform.controller;

import group.raber.dataform.exception.DataFormException;
import group.raber.dataform.handler.DataListHandler;
import group.raber.dataform.handler.DataSingleHandler;
import group.raber.dataform.handler.impl.BeanListHandler;
import group.raber.dataform.handler.impl.BeanSingleHandler;
import group.raber.dataform.handler.impl.DataBoxListHandler;
import group.raber.dataform.handler.impl.DataBoxSingleHandler;
import group.raber.dataform.model.DataForm;
import group.raber.dataform.service.DataFormService;
import group.raber.saber.holder.ApplicationContextHolder;
import group.raber.saber.holder.WebHolder;
import group.raber.saber.jdbc.query.PaginationQueryResult;
import group.raber.saber.kit.ValidateKit;
import group.raber.saber.lang.DataBox;
import group.raber.saber.lang.ValueObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created by tisir<yangsong158@qq.com> on 2017-05-30
 */
@RestController
@RequestMapping("/dataform")
public class DataFormController {
    @Autowired
    private DataFormService dataFormService;

    public DataFormService getDataFormService() {
        return dataFormService;
    }
    public void setDataFormService(DataFormService dataFormService) {
        this.dataFormService = dataFormService;
    }

    /**
     * 查询DataForm定义的元数据
     * @param form DataForm对象地址
     * @return
     */
    @GetMapping("/meta/{form}")
    public DataForm getDataForm(@PathVariable("form") String form){
        DataForm dataFormObject = dataFormService.getDataForm(form);
        return dataFormObject;
    }

    /**
     * <dt>分页查询</dt>
     * <dd>路径参数:form DataForm的{package}.{id}</dd>
     * <dd>路径参数:param DataForm的查询参数,格式为name1=value1;name2=value2,如果没有,写none</dd>
     * <dd>路径参数:sort DataForm的排序规则参数,格式为name1=asc,name2=desc,如果没有,写none</dd>
     * <dd>路径参数:size 分页大小,如果不分页,写0</dd>
     * <dd>路径参数:index 分页页码,从0开始</dd>
     * 所有的请求参数为filter参数
     * @param form DataForm对象地址
     * @param paramMatrix DataForm参数矩阵
     * @param sortMatrix DataForm排序矩阵
     * @param size 分页大小
     * @param index 分页页码(从0开始)
     * @return
     */
    @GetMapping("/data/list/{form}/{param}/{sort}/s{size:[\\d]+}p{index:[\\d]+}")
    public PaginationQueryResult<?> queryDataList(@PathVariable("form") String form
            , @MatrixVariable(pathVar = "param") Map<String, Object> paramMatrix
            , @MatrixVariable(pathVar = "sort") Map<String, String> sortMatrix
            , @PathVariable("size") Integer size, @PathVariable("index") Integer index
    ) {
        DataForm dataForm = dataFormService.getDataForm(form);
        ValidateKit.notNull(dataForm, "DataForm不存在,form=" + form);
        ValidateKit.notNull(dataForm.getHandler(), "DataForm不存在数据处理Handler,form=" + form);

        DataListHandler<?> dataListHandler = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
        ValidateKit.notNull(dataListHandler, "DataForm的数据处理Handler实例不存在,form=" + form);

//        Map<String, Object>
        Map<String, ValueObject> filterMap = WebHolder.getRequestParameterMap();

        System.out.println("query:" + paramMatrix);
        System.out.println("filter:" + filterMap);
        System.out.println("sort:" + sortMatrix);

        PaginationQueryResult<?> result = dataListHandler.query(dataForm, paramMatrix, filterMap,sortMatrix, size, index);
        return result;
    }

    /**
     * 查询单条记录
     * @param form DataForm对象地址
     * @param paramMatrix DataForm参数矩阵
     * @return
     */
    @GetMapping("/data/one/{form}")
    public Object queryDataOne(@PathVariable("form") String form,@MatrixVariable(pathVar = "param") Map<String, Object> paramMatrix) {
        DataForm dataForm = dataFormService.getDataForm(form);
        ValidateKit.notNull(dataForm, "DataForm不存在,form=" + form);
        ValidateKit.notNull(dataForm.getHandler(), "DataForm不存在数据处理Handler,form=" + form);

        DataSingleHandler<?> dataSingleHandler = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());

        return dataSingleHandler.query(dataForm,null);
    }

    /**
     * 保存列表
     * @param form DataForm对象地址
     * @param dataList 列表数据
     * @return
     */
    @PostMapping("/save/list/{form}/")
    public List<?> saveDataList(@PathVariable("form") String form, @RequestBody List<DataBox> dataList){
        //取数据以及dataform并进行相关的校验
        DataForm dataForm = dataFormService.getDataForm(form);
        ValidateKit.notNull(dataForm,"dataform not found:"+form);
        ValidateKit.notEmpty(dataList,"the list data is empty");
        //取绑定在dataform上的数据处理Handler
        DataListHandler<?> dataListHandler = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
        ValidateKit.notNull(dataListHandler, "dataform data processing Handler instance does not exist,form=" + form);

        if(dataListHandler instanceof DataBoxListHandler){
            DataBoxListHandler handler = (DataBoxListHandler)dataListHandler;
            handler.save(dataForm,(List)dataList);
        }else if(dataListHandler instanceof BeanListHandler){
            BeanListHandler<?> handler = (BeanListHandler)dataListHandler;
            handler.save(dataForm,(List)dataList);
        }else{
            throw new DataFormException("dataform processing class "+dataListHandler.getClass()+" is not legal");
        }


        return dataList;

    }

    /**
     * 保存单条记录
     * @param form DataForm对象地址
     * @param dataOne 数据对象
     * @return
     */
    @PostMapping("/save/one/{form}/")
    public Object saveDataOne(@PathVariable("form") String form, @RequestBody DataBox dataOne){
        //取数据以及dataform并进行相关的校验
        DataForm dataForm = dataFormService.getDataForm(form);
        ValidateKit.notNull(dataForm,"dataform not found:"+form);
        ValidateKit.notEmpty(dataOne,"the list data is empty");
        //取绑定在dataform上的数据处理Handler
        DataSingleHandler<?> dataSingleHandler = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
        ValidateKit.notNull(dataSingleHandler, "dataform data processing Handler instance does not exist,form=" + form);

        if(dataSingleHandler instanceof DataBoxSingleHandler){
            DataBoxSingleHandler handler = (DataBoxSingleHandler)dataSingleHandler;
            handler.save(dataForm,(DataBox)dataOne);
        }else if(dataSingleHandler instanceof BeanSingleHandler){
//            BeanSingleHandler<?> handler = (BeanSingleHandler)dataSingleHandler;
//            handler.save(dataForm,dataOne);
        }else{
            throw new DataFormException("dataform processing class "+dataSingleHandler.getClass()+" is not legal");
        }


        return dataOne;

    }

    /**
     * 删除列表数据
     * @param form DataForm对象地址
     * @param dataList 列表数据对象
     * @return
     */
    @PostMapping("/delete/list/{form}/")
    public int deleteDataList(@PathVariable("form") String form, @RequestBody List<DataBox> dataList){
        return 0;
    }

    /**
     * 删除单个数据
     * @param form DataForm对象地址
     * @param dataOne 数据对象
     * @return
     */
    @PostMapping("/delete/one/{form}/")
    public int deleteDataOne(@PathVariable("form") String form, @RequestBody DataBox dataOne){
        return 0;
    }

    /**
     * 调用列表绑定DataHandler的方法
     * @param form DataForm对象地址
     * @param method DataHandler的方法名
     * @param dataList 数据列表
     * @return
     */
    @PostMapping("/invoke/list/{form}/{method}")
    public Object invokeDataListHandlerMethod(@PathVariable("form") String form,@PathVariable("method") String method, @RequestBody List<DataBox> dataList){
        return null;
    }

    /**
     * 调用列表绑定DataHandler的方法
     * @param form DataForm对象地址
     * @param method DataHandler的方法名
     * @param dataOne 数据对象
     * @return
     */
    @PostMapping("/invoke/one/{form}/{method}")
    public Object invokeDataOneHandlerMethod(@PathVariable("form") String form,@PathVariable("method") String method, @RequestBody DataBox dataOne){
        return null;
    }

    /**
     * 服务端校验列表数据
     * @param form DataForm对象地址
     * @param dataList 数据对象列表
     * @return
     */
    @PostMapping("/validate/list/{form}")
    public Object validateDataList(@PathVariable("form") String form, @RequestBody List<DataBox> dataList){
        return null;
    }

    /**
     * 服务端校验数据对象
     * @param form DataForm对象地址
     * @param dataOne 数据对象
     * @return
     */
    @PostMapping("/validate/one/{form}")
    public Object validateDataOne(@PathVariable("form") String form, @RequestBody DataBox dataOne){
        return null;
    }



}
